<template>
  <div class="bc">
    <template v-for="(item, index) in routArr">
      <div class="name" :key="item.name">
        {{ $t(item.name) }}
      </div>
      <div class="tip" :key="index">{{ index == 0 ? ':' : '>' }}</div>
    </template>
    <div class="last-path">{{ $t(lastPath.name) }}</div>
  </div>
</template>

<script lang="ts">
import Vue from 'vue';
import { Component, Watch } from 'vue-property-decorator';

@Component({
  components: {},
})
export default class BreadcrumbComponent extends Vue {
  routArr = [] as object[];
  lastPath: any = {};

  mounted() {
    this.initPage();
  }

  @Watch('$route', { deep: true })
  async onChangeRoute(to: any, from: any) {
    this.initPage();
  }

  initPage() {
    this.routArr = [];
    this.$route.matched.forEach((routObj: any, index: any) => {
      if (index === 0) {
        routObj.name = this.$t('位置');
        routObj.path = '';
      }

      const rObj: any = {
        name: routObj.name,
        path: routObj.path,
      };

      if (rObj.name) {
        this.routArr.push(rObj);
      }
    });
    if (this.routArr.length > 1) {
      this.lastPath = this.routArr[this.routArr.length - 1];
    } else {
      this.lastPath = this.routArr[0];
    }
    this.routArr.pop();
  }
}
</script>

<style scoped lang="less">
@import './index.less';
</style>
